package com.sweets.look.ui.setting;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import com.sweet.satellite.TranslucentSBActivity;
import com.sweets.look.R;
import com.sweets.look.adapter.RuleItem;
import com.sweets.look.constant.Constants;
import com.sweets.look.database.DatabaseHandler;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.activity.BrowserActivity;
import com.sweets.look.ui.widget.MarkDialog;
import com.sweets.look.ui.widget.MarkEditDialog;
import com.sweets.look.ui.widget.MarkEditDialog.OnCustomDialogListener;
import com.sweets.look.util.ViewUtils;

/**
 * 广告标记
 */
public class BlockSettings extends TranslucentSBActivity {
    private class ViewHolder {
        public TextView tags;
        public TextView url;
    }

    private Activity mActivity;
    private ArrayAdapter<RuleItem> mAdapter;
    private Context mContext;
    private List<RuleItem> mData;
    private DatabaseHandler mDatabaseHandler;
    private PreferenceManager mPreferences;


    private void addRule(final String url, final String tags) {
        RuleItem v0 = new RuleItem();
        v0.setUrl(url);
        v0.setTags(tags);
        this.mData.add(v0);
        new Thread(new Runnable() {
            public void run() {
                if (mDatabaseHandler == null) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                } else if (!mDatabaseHandler.isOpen()) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                }

                mDatabaseHandler.visitAdsItem(url, tags, false);
            }
        }).start();
        this.mAdapter.notifyDataSetChanged();
    }

    private void clearAllAdRules() {
        this.mData.clear();
        new Thread(new Runnable() {
            public void run() {
                if (mDatabaseHandler == null) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                } else if (!mDatabaseHandler.isOpen()) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                }

                mDatabaseHandler.deleteAllAdRules();
            }
        }).start();
        this.mAdapter.notifyDataSetChanged();
    }

    private void initAdsList() {
        if (this.mDatabaseHandler == null) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        } else if (!this.mDatabaseHandler.isOpen()) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        }

        ListView v0 = (ListView) this.findViewById(R.id.adsList);
        this.mData = this.mDatabaseHandler.getAllAdsItems();
        this.mAdapter = new ArrayAdapter<RuleItem>(this.mContext, R.layout.widget_ads_row, this.mData) {
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;
                if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.widget_ads_row, parent,
                            false);
                    viewHolder = new ViewHolder();
                    viewHolder.url = (TextView) convertView.findViewById(R.id.ads_url);
                    viewHolder.tags = (TextView) convertView.findViewById(R.id.ads_rule);
                    convertView.setTag(viewHolder);
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }

                RuleItem v1 = mData.get(position);
                viewHolder.url.setText(v1.getUrl());
                viewHolder.tags.setText(v1.getTags());
                return convertView;
            }
        };
        v0.setAdapter(this.mAdapter);
        v0.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView arg5, View view, final int position, long id) {
                RuleItem v0 = mData.get(position);
                new MarkEditDialog(mContext).builder()
                        .setTitle(BlockSettings.this
                                .getResources().getString(R.string.add_rule))
                        .setCanceledOnTouchOutside(false).setTitleHint(
                        getResources().getString(R.string.hint_url), v0.getUrl())
                        .setMsgHint(getResources().getString(R.string.hint_tags),
                                v0.getTags())
                        .setPositiveButton(getResources().getString(
                                R.string.action_ok), new OnCustomDialogListener() {
                            public void back(String url, String tags, String other) {
                                operateRule(position, url, tags);
                            }
                        }).setNegativeButton(getResources().getString(R.string.action_no), null).
                        show();
            }
        });
        v0.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView arg6, View view, final int i, long l) {
                Object v0 = mData.get(i);
                new MarkDialog(mContext).builder()
                        .setTitle(getResources()
                                .getString(R.string.action_delete)).setCanceledOnTouchOutside(true)
                        .setMessage(((RuleItem)
                                v0).getUrl() + "\n\n" + ((RuleItem) v0).getTags()).setPositiveButton(BlockSettings
                        .this.getResources().getString(R.string.action_ok), new View.OnClickListener() {
                    public void onClick(View view) {
                        operateRule(i, "", "");
                    }
                }).setNegativeButton(getResources().getString(R.string.action_no), null).
                        show();
                return true;
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.settings_block);
        this.setToolbarTitle(R.string.settings_ad_rules);

        this.mActivity = this;
        this.mContext = this;
        this.mPreferences = PreferenceManager.getInstance();
        ViewUtils.swipeToFinish(this.findViewById(R.id.settingLayout), this);
        this.initAdsList();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (this.mDatabaseHandler != null && (this.mDatabaseHandler.isOpen())) {
            this.mDatabaseHandler.close();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.mDatabaseHandler == null) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        } else if (!this.mDatabaseHandler.isOpen()) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        }
    }

    public void onSettingsItemClick(View v) {
        View.OnClickListener v5 = null;
        int v4 = R.string.action_ok;
        int v3 = R.string.action_no;
        switch (v.getId()) {
            case R.id.layoutClearRules: {
                new MarkDialog(this.mContext).builder()
                        .setTitle(this.getResources().getString(R.string.clear_ad_rules))
                        .setMessage(this.getResources().getString(R.string.cannot_undo))
                        .setPositiveButton(this.getResources().getString(v4),
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        clearAllAdRules();
                                    }
                                }).setNegativeButton(this.getResources().getString(v3), v5).show();
                break;
            }
            case R.id.layoutAddRule: {
                new MarkEditDialog(this.mContext).builder()
                        .setTitle(this.getResources().getString(R.string.add_rule))
                        .setCanceledOnTouchOutside(false)
                        .setTitleHint(this.getResources().getString(R.string.hint_url), "")
                        .setMsgHint(this.getResources().getString(R.string.hint_tags), "")
                        .setPositiveButton(this.getResources().getString(v4), new OnCustomDialogListener() {
                            @Override
                            public void back(String url, String tag, String other) {
                                addRule(url, tag);
                            }
                        }).setNegativeButton(this.getResources().getString(v3), v5).show();
                break;
            }
            case R.id.layoutGetRules: {
                this.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(Constants.URL_RULES_API),
                        this.mContext, BrowserActivity.class));
                break;
            }
        }
    }


    private void operateRule(int pos, final String url, final String tags) {
        final RuleItem item = this.mData.get(pos);
        if (url.equalsIgnoreCase("")) {
            this.mData.remove(item);
        } else if (!tags.equalsIgnoreCase("")) {
            item.setUrl(url);
            item.setTags(tags);
        } else {
            this.mData.remove(item);
        }

        new Thread(new Runnable() {
            public void run() {
                if (mDatabaseHandler == null) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                } else if (!mDatabaseHandler.isOpen()) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                }

                if ((url.equalsIgnoreCase("")) || (tags.equalsIgnoreCase(""))) {
                    mDatabaseHandler.deleteAdsItem(item.getUrl());
                } else {
                    mDatabaseHandler.visitAdsItem(url, tags, true);
                }
            }
        }).start();
        this.mAdapter.notifyDataSetChanged();
    }
}

